import Axios from 'axios'
import { ElMessage } from 'element-plus'
import baseUrl from './baseUrl'
import { getStorage, removeStorage } from '@/utils/auth'
interface AxiosResponseOld<T = any> {
  code?: number
  data: any
  message?: string
  msg?: string
  responseId?: any
  success?: boolean
  extra?: T
}
interface AxiosResponse<T = any> extends AxiosResponseOld<T> {}
const axios = Axios.create({
  baseURL: baseUrl,
  timeout: 20000
})

// 允许携带 cookie
axios.defaults.withCredentials = true
// 设置请求头 headers
// axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
// 默认使用 application/json 形式
axios.defaults.headers.post['Content-Type'] = 'application/json'

// 请求拦截器
axios.interceptors.request.use(
  (config: any) => {
    const token: string = getStorage('USER_TOKEN') || ''
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  (err: any) => Promise.reject(err)
)

// 响应拦截器
axios.interceptors.response.use(
  (res: AxiosResponseOld) => {
    const { data } = res
    const code = Number(data['code'] || 200)
    if (code !== 200) {
      if (code === 401) {
        removeStorage('USER_TOKEN')
        location.reload()
      }
      ElMessage.closeAll()
      ElMessage({
        message: data.msg || data.message || data.data || 'error',
        showClose: true,
        type: 'error',
        duration: 4000
      })
      return Promise.reject(data.status)
    }
    if (code === 200) {
      console.log(data)
      return data
    }
  },
  (err: any) => {
    // 对响应错误做点什么
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误'
          break
        case 401:
          err.message = '登录过期，请登录'
          removeStorage('USER_TOKEN')
          location.reload()
          break
        case 403:
          err.message = '拒绝访问'
          break
        case 404:
          err.message = `请求地址出错: ${err.response.config.url}`
          break
        case 408:
          err.message = '请求超时'
          break
        case 500:
          err.message = '服务器内部错误'
          break
        case 501:
          err.message = '服务未实现'
          break
        case 502:
          err.message = '网关错误'
          break
        case 503:
          err.message = '服务不可用'
          break
        case 504:
          err.message = '网关超时'
          break
        case 505:
          err.message = 'HTTP版本不受支持'
          break
        default:
          err.message = '系统错误'
          break
      }
    } else {
      err.message = '请求失败！'
    }
    ElMessage.closeAll()
    ElMessage({
      message: err.message,
      showClose: true,
      type: 'error',
      duration: 4000
    })
    // 对响应错误做点什么
    return Promise.reject(err)
  }
)
export default axios
